import { uploadFileWithFormData, setOperationLog } from '../api/api';
import _ from 'lodash';
import store from '../store/index';
import moment from 'moment';
export const filterAgentState = agentState => {
	let state = '';
	switch (agentState) {
		case 'offline':
			state = '下线';
			break;
		case 'notReady':
			state = '示忙';
			break;
		case 'ready':
			state = '示闲';
			break;
		case 'ringing':
			state = '振铃中';
			break;
		case 'serving':
			state = '会话中';
			break;
		case 'afterWork':
			state = '话后整理';
			break;
		case 'otherWork':
			state = '小休';
			break;
		default:
			state = '';
			break;
	}
	return state;
};
//分割字符串
//例:
//str: scanCode_1
//key:'_'
//originStr:scancode
//replaceStr:推送扫码
//return: 推送扫码1
export const subStringAndReplaceName = (str, key, originStr, replaceStr) => {
	if (!str) {
		return;
	}
	let index = str.indexOf(key);
	if (index !== -1) {
		let Number = str.substr(index + 1, str.length - index - 1);
		if (originStr === str.substr(0, index)) {
			return replaceStr + Number;
		}
		return str;
	}
	return str;
};

/**
 * 根据对象属性进行冒泡排序
 * @param { Array } arr 原始数组
 * @param { string } prop 对象属性
 * @returns 新的数组
 */

export const popSortByProperty = (arr, prop) => {
	let result = JSON.parse(JSON.stringify(arr));
	let len = result.length;
	for (let k = 0; k < len - 1; k++) {
		for (let m = 0; m < len - k - 1; m++) {
			if (result[m][prop] > result[m + 1][prop]) {
				let val = result[m];
				result[m] = result[m + 1];
				result[m + 1] = val;
			}
		}
	}
	return result;
};

/**
 * 分割表单数组
 * @param { Array } arr 原始数组
 * @param { Number } maxLength 从哪一位开始分割
 * @returns 两个新的数组
 */

export const spliceFormList = (arr, maxLength) => {
	let arrLength = 0;
	let newArray = [];
	let firstString = [];
	let secondString = [];
	let firstArray = [];
	let secondArray = [];
	let firstStringLength = 0;
	let formList = [];
	if (arr.length === 0) {
		return { firstString, secondString };
	}
	arr.forEach(item => {
		newArray.push(item.name + ';');
		formList.push({ name: item.name + ';', id: item.id });
	});
	for (let i = 0; i < newArray.length; i++) {
		arrLength = arrLength + newArray[i].length;
		if (arrLength <= maxLength) {
			firstString.push(newArray[i]);
		} else {
			secondString.push(newArray[i]);
		}
	}
	formList.forEach(item => {
		for (let i = 0; i < firstString.length; i++) {
			if (item.name === firstString[i]) {
				firstArray.push({ name: item.name, id: item.id });
			}
		}
		for (let i = 0; i < secondString.length; i++) {
			if (item.name === secondString[i]) {
				secondArray.push({ name: item.name, id: item.id });
			}
		}
	});
	for (let i = 0; i < firstString.length; i++) {
		firstStringLength = firstStringLength + firstString[i].length;
	}
	if (secondString.length !== 0) {
		if (firstStringLength < maxLength) {
			maxLength = maxLength - firstStringLength;
			let g = '';
			secondString.forEach(item => {
				g = g + item;
			});
			firstArray.push({ name: g.substring(0, maxLength), id: secondArray[0].id });
		}
	}
	return { firstArray, secondArray };
};

/**
 * 防抖函数
 * @param { Fucntion } callback  回调函数
 * @param {*} time 时长
 * @returns
 */
export function debounce(callback, time) {
	// 声明一个 timerId 用来存储定时器
	let timerId = null;
	return function () {
		// 判断 timerId 是否存在, 存在则清除
		if (timerId) {
			clearTimeout(timerId);
		}
		timerId = setTimeout(() => {
			callback.apply(this, arguments);
			// 重置定时器变量
			timerId = null;
		}, time);
	};
}

/** 计算文件大小 */
export const getFileSize = size => {
	let count = 0;
	let total = size / 1024;
	let result = '';
	while (total > 1024) {
		total = total / 1024;
		count++;
	}
	switch (count) {
		case 0:
			result = total.toFixed(2) + 'KB';
			break;
		case 1:
			result = total.toFixed(2) + 'MB';
			break;
		case 2:
			result = total.toFixed(2) + 'G';
			break;
		case 3:
			result = total.toFixed(2) + 'T';
			break;
		default:
			break;
	}
	return result;
};

/** 上传文件到服务器 */
export const uploadFile = async file => {
	return new Promise((resolve, reject) => {
		let formData = new FormData();
		formData.append('file', file);
		uploadFileWithFormData(formData)
			.then(res => {
				const { data } = res;
				resolve({ url: data.data.url, size: file.size, name: file.name });
			})
			.catch(err => {
				reject(err);
			});
	});
};

/** 切割字符串 */
export const splitString = str => {
	let index = str.indexOf('.');
	let replaceName = str.substring(0, index);
	let suffix = str.substring(index, str.length);
	console.log(replaceName, suffix);
	if (replaceName.length > 20) {
		let first = replaceName.substring(0, 10);
		let last = replaceName.substring(replaceName.length, replaceName.length - 1);
		return first + '...' + last + suffix;
	}
	return str;
};

// 计算字符串的长度，中文算2个，英文算1个
export const getStringLenth = function (str) {
	// eslint-disable-next-line
	if (str == null) return 0;
	if (typeof str !== 'string') {
		// eslint-disable-next-line
		str = str + '';
	}
	// eslint-disable-next-line
	return str.replace(/[^\x00-\xff]/g, '01').length;
};

// 字符串中插入字符
export const insertStr = (soure = '', dom = {}, newStr = '') => {
	const soureCurrent = soure === null ? '' : soure;
	console.log({ soure, dom, newStr });
	const newStrLength = newStr.length;
	if (dom && dom.setSelectionRange) {
		let start = dom.selectionStart;
		setTimeout(() => {
			dom.focus();
			dom.setSelectionRange && dom.setSelectionRange(start + newStrLength, start + newStrLength, 'none');
		});
		return soureCurrent.slice(0, start) + newStr + soureCurrent.slice(start);
	} else {
		store.dispatch('variable/setInsertVariable', { id: dom.id, variable: newStr });
		return soure;
	}
};

export const backupData = data => {
	return _.cloneDeep(data);
};

/**
 * 清除 接口undefined 属性
 * @param {*} params
 * @returns
 */
const isFalsy = value => (value === 0 ? false : !value);
export const cleanParams = params => {
	const result = { ...params };
	Object.keys(result).forEach(key => {
		const value = result[key];
		if (isFalsy(value)) {
			delete result[key];
		}
	});

	return result;
};

/**
 * 设置操作日志留痕
 * @param {*} params {type:类型 0：登入登出 1:运营管理,category:分类 downloadAndExport：下载&导出，logInOrOut：登入/登出,content:内容}
 */
export const setOperationLogFuntion = async params => {
	try {
		const { data } = await setOperationLog(params);
		if (data.code === 200) {
			console.log('set operation log success');
		} else {
			console.log('set operation log failed');
		}
	} catch (error) {
		console.log(error, 'set operation log failed');
	}
};

/** 过滤表单记录 */
export const filterFormRecord = records => {
	if (!Array.isArray(records)) return [];
	return records.map(record => ({
		id: record.id,
		formNumber: record.followId,
		agentId: record.fromClient && record.fromClient.externalUserInfo && record.fromClient.externalUserInfo.name ? record.fromClient.externalUserInfo.name : '-',
		agentName: record.fromClient && record.fromClient.userName ? record.fromClient.userName : '-',
		pushTime: moment(record.createdAt).format('YYYY-MM-DD HH:mm:ss'),
		formStatus: record.status === 'success' ? '提交成功' : record.status === 'fail' ? '提交失败' : record.status === 'timeout' ? '提交超时' : '-',
		status: record.status,
		formHistoryDetails: record.formHistoryDetails, // 提交的详情
		formHistoryTemplates: record.formHistoryTemplates // 提交的所有表单
	}));
};

/** 屏幕水印 */
export const addScreenWatermark = (option = {}) => {
	if (store.state.login.userInfo.userId) {
		let text = '';
		if (option.content.includes('username') || !option.hasOwnProperty('content')) {
			text = text + localStorage.getItem(`zco_admin_userName_${window.uid}`);
		}
		if (option.content.includes('loginTime') || !option.hasOwnProperty('content')) {
			const localDate = moment(store.state.login.userInfo.loginTime).format('YYYY-MM-DD HH:mm:ss'); // 格式化时间戳
			text = text + ' ' + localDate;
		}
		option.txt = text;
	} else {
		option.txt = '';
	}
	if (option.hasOwnProperty('alpha')) {
		option.alpha = option.alpha / 100;
	}
	dstpSecurityPage.createWatermarking(option);
};

/** 去除屏幕水印 */
export const removeScreenWatermark = () => {
	dstpSecurityPage.createWatermarking({ txt: '' });
};

/**
 * 获取指定的URL中的参数值。
 * @param {*} url 
 * @returns 
 */
export const appendToken = (url) => {
	if (!url) {
	  return url;
	}
	// OSSAccessKeyId=
	if (url.indexOf('OSSAccessKeyId=') > -1) {
	  return url;
	}
	// 如果url中已经有token，则不再追加	token
	if (url.indexOf('token=') > -1) {
		return url;
	}
	const token = localStorage.getItem(`zco_admin_token_${window.uid}`)
	const separator = url.includes('?') ? '&' : '?';
	return `${url}${separator}token=${token}`;
  }

/**
 * 从指定的URL中移除token参数
 * @param {*} url 
 * @returns 
 */
export const removeToken = (url) => {
	if (!url) {
		return url;
	}
	// 如果url中没有token
	if (url.indexOf('token=') < 0) {
		return url;
	}
	function removeQueryParam(url, param) {
		// 构建正则表达式，用于匹配并删除指定的参数
		let regex = new RegExp(`[?&]${param}=[^&]*`, 'g');
		// 先移除参数，再处理可能多余的符号
		let cleanUrl = url.replace(regex, '').replace(/&$/, '').replace(/\?$/, '');
	
		// 如果有多个参数，并且移除了第一个参数，可能需要调整 ? 和 & 的位置
		if (cleanUrl.indexOf('?&') !== -1) {
			cleanUrl = cleanUrl.replace('?&', '?');
		}
	
		return cleanUrl;
	}
	return removeQueryParam(url, 'token');
};
